import { HomePath } from '@/config'
import { useStore } from '@/store'
import { DownOutlined } from '@ant-design/icons'
import { Button, Dropdown, Menu, MenuProps, Tabs } from 'antd'
import { observer } from 'mobx-react'
import { useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'

const TagList = () => {
  const { tagStore }: any = useStore()
  const navigate = useNavigate()
  const { pathname } = useLocation()
  const [activeKey, setActiveKey] = useState(HomePath)
  const [items, setItems] = useState(tagStore.tagList)

  // 设置当前tab状态
  useEffect(() => {
    setActiveKey(pathname)
  }, [pathname])

  // 点击后更新tab
  useEffect(() => {
    setItems(tagStore.tagList)
  }, [tagStore.tagList])

  const handleClick = (key: string) => {
    navigate(key)
    setActiveKey(key)
  }

  // 获取当前索引
  const getTargetIndex = (targetKey: string) => tagStore.tagList.findIndex((pane: any) => pane.key === targetKey)

  // 删除tab
  const handleRemove = (targetKey: string) => {
    const { tagList }: any = tagStore
    const targetIndex = getTargetIndex(targetKey)
    const newPanes = tagList.filter((pane: any) => pane.key !== targetKey)

    if (newPanes.length && targetKey === activeKey) {
      const { key } = newPanes[targetIndex === newPanes.length ? targetIndex - 1 : targetIndex]
      setActiveKey(key)
    }

    tagStore.deleteTag(targetKey)
    setItems(newPanes)
  }

  // 处理删除
  const onEdit = (key: any, action: any) => {
    if (action === 'remove') {
      handleRemove(key)
    }
  }

  const onCloseMenu: MenuProps['onClick'] = ({ key }: any) => {
    switch (key) {
      case '1':
        tagStore.closeRightTags(activeKey, getTargetIndex(activeKey))
        break
      case '2':
        tagStore.closeOtherTag(activeKey)
        break
      case '3':
        tagStore.emptyTag()
        break
      default:
        console.log('default')
    }
  }

  // 下拉菜单
  const tagCloseMenu = (
    <Menu
      onClick={onCloseMenu}
      items={[
        {
          key: '1',
          label: '关闭右侧',
        },
        {
          key: '2',
          label: '关闭其它',
        },
        {
          key: '3',
          label: '关闭全部',
        },
      ]}
    />
  )

  // 右扩展
  const opertationExtra = (
    <>
      <Dropdown dropdownRender={() => tagCloseMenu}>
        <Button icon={<DownOutlined />} />
      </Dropdown>
    </>
  )

  return (
    <div className="app-tag-view tags-wrap">
      <Tabs
        hideAdd
        tabBarExtraContent={{ right: opertationExtra }}
        type="editable-card"
        activeKey={activeKey}
        onChange={handleClick}
        onEdit={onEdit}
        items={items}
      />
    </div>
  )
}

export default observer(TagList)
